<template>
  <div class="teacher-page">
    <a-page-header title="教员管理" sub-title="查看和管理教员信息" />
    
    <a-card class="card-shadow">
      <!-- 搜索栏 -->
      <a-form layout="inline" class="search-form">
        <a-form-item label="教员姓名">
          <a-input v-model:value="searchForm.name" placeholder="请输入姓名" />
        </a-form-item>
        
        <a-form-item label="学校">
          <a-input v-model:value="searchForm.school" placeholder="请输入学校" />
        </a-form-item>
        
        <a-form-item label="状态">
          <a-select v-model:value="searchForm.status" style="width: 120px">
            <a-select-option value="">全部</a-select-option>
            <a-select-option value="ACTIVE">正常</a-select-option>
            <a-select-option value="DISABLED">禁用</a-select-option>
          </a-select>
        </a-form-item>
        
        <a-form-item>
          <a-space>
            <a-button type="primary" @click="handleSearch">
              <template #icon><search-outlined /></template>
              搜索
            </a-button>
            <a-button @click="handleReset">重置</a-button>
          </a-space>
        </a-form-item>
      </a-form>
      
      <!-- 表格 -->
      <a-table
        :columns="columns"
        :data-source="dataSource"
        :loading="loading"
        :pagination="pagination"
        :row-key="record => record.id"
        :scroll="{ x: 1800 }"
        class="teacher-table"
        @change="handleTableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'avatar'">
            <a-avatar :src="record.avatarUrl || 'https://api.dicebear.com/7.x/avataaars/svg?seed=' + record.id" :size="48" />
          </template>
          
          <template v-else-if="column.key === 'info'">
            <div>
              <div><strong>{{ record.realName || '未设置' }}</strong></div>
              <div style="color: #999; font-size: 12px;">{{ record.mobile || '-' }}</div>
            </div>
          </template>
          
          <template v-else-if="column.key === 'education'">
            <div>
              <div>{{ record.school || '-' }}</div>
              <div style="color: #999; font-size: 12px;">{{ record.education || '-' }}</div>
            </div>
          </template>
          
          <template v-else-if="column.key === 'subjects'">
            <a-space wrap>
              <a-tag 
                v-for="(subject, index) in parseSubjects(record.subjects)" 
                :key="index" 
                color="blue"
                style="margin-bottom: 4px;"
              >
                {{ subject }}
              </a-tag>
              <span v-if="!record.subjects || parseSubjects(record.subjects).length === 0" style="color: #999;">未设置</span>
            </a-space>
          </template>
          
          <template v-else-if="column.key === 'grades'">
            <a-space wrap>
              <a-tag 
                v-for="(grade, index) in parseGrades(record.grades)" 
                :key="index" 
                color="green"
                style="margin-bottom: 4px;"
              >
                {{ grade }}
              </a-tag>
              <span v-if="!record.grades || parseGrades(record.grades).length === 0" style="color: #999;">未设置</span>
            </a-space>
          </template>
          
          <template v-else-if="column.key === 'experienceYears'">
            <a-tag color="purple">{{ record.experienceYears || 0 }}年</a-tag>
          </template>
          
          <template v-else-if="column.key === 'hourlyRate'">
            <span style="color: #ff6b6b; font-weight: bold;">¥{{ record.hourlyRate || 0 }}</span>
          </template>
          
          <template v-else-if="column.key === 'createdAt'">
            <span style="color: #666; font-size: 13px;">{{ formatDate(record.createdAt) }}</span>
          </template>
          
          <template v-else-if="column.key === 'rating'">
            <div>
              <a-rate :value="parseFloat(record.rating)" disabled allow-half style="font-size: 14px;" />
              <div style="margin-top: 4px; font-size: 12px; color: #666;">
                {{ parseFloat(record.rating || 0).toFixed(1) }} 分
              </div>
            </div>
          </template>
          
          <template v-else-if="column.key === 'verified'">
            <a-tag :color="record.verified ? 'green' : 'orange'">
              {{ record.verified ? '已认证' : '未认证' }}
            </a-tag>
          </template>
          
          <template v-else-if="column.key === 'status'">
            <a-tag :color="record.status === 'ACTIVE' ? 'green' : 'red'">
              {{ record.status === 'ACTIVE' ? '正常' : '禁用' }}
            </a-tag>
          </template>
          
          <template v-else-if="column.key === 'action'">
            <a-space>
              <a-button type="link" size="small" @click="handleView(record)">
                详情
              </a-button>
              <a-button
                type="link"
                :danger="record.status === 'ACTIVE'"
                size="small"
                @click="handleToggleStatus(record)"
              >
                {{ record.status === 'ACTIVE' ? '禁用' : '启用' }}
              </a-button>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>
    
    <!-- 教员详情弹窗 -->
    <a-modal
      v-model:open="detailModalVisible"
      title="教员详情"
      width="800px"
      :footer="null"
    >
      <a-descriptions :column="2" bordered size="small">
        <a-descriptions-item label="姓名">
          <strong>{{ currentTeacher.realName || currentTeacher.username }}</strong>
        </a-descriptions-item>
        <a-descriptions-item label="手机号">{{ currentTeacher.mobile || '-' }}</a-descriptions-item>
        
        <a-descriptions-item label="学校">{{ currentTeacher.school || '-' }}</a-descriptions-item>
        <a-descriptions-item label="学历">{{ currentTeacher.education || '-' }}</a-descriptions-item>
        
        <a-descriptions-item label="擅长科目" :span="2">
          <a-space wrap>
            <a-tag v-for="(subject, index) in parseSubjects(currentTeacher.subjects)" :key="index" color="blue">
              {{ subject }}
            </a-tag>
            <span v-if="!currentTeacher.subjects">未设置</span>
          </a-space>
        </a-descriptions-item>
        
        <a-descriptions-item label="可教年级" :span="2">
          <a-space wrap>
            <a-tag v-for="(grade, index) in parseGrades(currentTeacher.grades)" :key="index" color="green">
              {{ grade }}
            </a-tag>
            <span v-if="!currentTeacher.grades">未设置</span>
          </a-space>
        </a-descriptions-item>
        
        <a-descriptions-item label="教学经验">
          <a-tag color="purple">{{ currentTeacher.experienceYears || 0 }}年</a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="时薪">
          <span style="color: #ff6b6b; font-weight: bold; font-size: 16px;">¥{{ currentTeacher.hourlyRate || 0 }}/时</span>
        </a-descriptions-item>
        
        <a-descriptions-item label="评分">
          <a-rate :value="parseFloat(currentTeacher.rating || 0)" disabled allow-half />
          <span style="margin-left: 8px;">{{ parseFloat(currentTeacher.rating || 0).toFixed(1) }} 分</span>
        </a-descriptions-item>
        <a-descriptions-item label="完成订单">
          <a-tag color="cyan">{{ currentTeacher.orderCount || 0 }}单</a-tag>
        </a-descriptions-item>
        
        <a-descriptions-item label="服务学员">
          <a-tag color="orange">{{ currentTeacher.studentCount || 0 }}人</a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="认证状态">
          <a-tag :color="currentTeacher.verified ? 'green' : 'orange'">
            {{ currentTeacher.verified ? '已认证' : '未认证' }}
          </a-tag>
        </a-descriptions-item>
        
        <a-descriptions-item label="账号状态">
          <a-tag :color="currentTeacher.status === 'ACTIVE' ? 'green' : 'red'">
            {{ currentTeacher.status === 'ACTIVE' ? '正常' : '禁用' }}
          </a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="注册时间">
          {{ formatDate(currentTeacher.createdAt) }}
        </a-descriptions-item>
        
        <a-descriptions-item label="个人简介" :span="2">
          <div style="max-height: 200px; overflow-y: auto; padding: 8px; background: #f5f5f5; border-radius: 4px;">
            {{ currentTeacher.intro || '暂无介绍' }}
          </div>
        </a-descriptions-item>
      </a-descriptions>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { message, Modal } from 'ant-design-vue'
import { SearchOutlined } from '@ant-design/icons-vue'
import { getAdminTeacherList, updateTeacherStatus, getTeacherDetail } from '@/api/teacher'

const loading = ref(false)
const detailModalVisible = ref(false)
const currentTeacher = ref({})

const searchForm = reactive({
  keyword: '',
  status: '',
  identityStatus: ''
})

const columns = [
  { title: '头像', key: 'avatar', width: 80 },
  { title: '基本信息', key: 'info', width: 150 },
  { title: '学历背景', key: 'education', width: 180 },
  { title: '擅长科目', key: 'subjects', width: 200 },
  { title: '可教年级', key: 'grades', width: 200 },
  { title: '教学经验', key: 'experienceYears', width: 100, align: 'center' },
  { title: '时薪', key: 'hourlyRate', width: 100, align: 'right' },
  { title: '评分', key: 'rating', width: 150, align: 'center' },
  { title: '完成订单', dataIndex: 'orderCount', key: 'orderCount', width: 100, align: 'center' },
  { title: '服务学员', dataIndex: 'studentCount', key: 'studentCount', width: 100, align: 'center' },
  { title: '认证状态', key: 'verified', width: 100, align: 'center' },
  { title: '账号状态', key: 'status', width: 100, align: 'center' },
  { title: '注册时间', key: 'createdAt', width: 160 },
  { title: '操作', key: 'action', width: 180 }
]

const dataSource = ref([])

const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showTotal: (total) => `共 ${total} 条`
})

const loadData = async () => {
  loading.value = true
  
  try {
    const params = {
      page: pagination.current,
      size: pagination.pageSize,
      ...searchForm
    }
    
    const res = await getAdminTeacherList(params)
    
    if (res.data) {
      dataSource.value = res.data.list || []
      pagination.total = res.data.total || 0
      
      // 处理数据格式
      dataSource.value.forEach(item => {
        // 确保 subjects 是字符串
        if (Array.isArray(item.subjects)) {
          item.subjects = item.subjects.join(',')
        }
        // 添加状态字段
        item.status = item.status || 'ACTIVE'
      })
    }
  } catch (error) {
    message.error(error.message || '加载数据失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.current = 1
  loadData()
}

const handleReset = () => {
  Object.assign(searchForm, {
    keyword: '',
    status: '',
    identityStatus: ''
  })
  pagination.current = 1
  loadData()
}

const handleTableChange = (pag) => {
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
  loadData()
}

const handleView = async (record) => {
  try {
    const res = await getTeacherDetail(record.id)
    if (res.data) {
      currentTeacher.value = res.data
      detailModalVisible.value = true
    }
  } catch (error) {
    message.error('获取教员详情失败')
  }
}

const handleToggleStatus = (record) => {
  const newStatus = record.status === 'ACTIVE' ? 'DISABLED' : 'ACTIVE'
  const statusText = newStatus === 'ACTIVE' ? '启用' : '禁用'
  
  Modal.confirm({
    title: '确认操作',
    content: `确定要${statusText}教员 ${record.realName || record.username} 吗？`,
    onOk: async () => {
      try {
        await updateTeacherStatus(record.id, newStatus)
        record.status = newStatus
        message.success('状态更新成功')
      } catch (error) {
        message.error(error.message || '状态更新失败')
      }
    }
  })
}

// 解析科目（支持JSON数组和逗号分隔）
const parseSubjects = (subjects) => {
  if (!subjects) return []
  try {
    // 尝试解析JSON
    if (subjects.startsWith('[')) {
      return JSON.parse(subjects)
    }
    // 逗号分隔
    return subjects.split(',').filter(s => s.trim())
  } catch {
    return subjects.split(',').filter(s => s.trim())
  }
}

// 解析年级（支持JSON数组和逗号分隔）
const parseGrades = (grades) => {
  if (!grades) return []
  try {
    // 尝试解析JSON
    if (grades.startsWith('[')) {
      return JSON.parse(grades)
    }
    // 逗号分隔
    return grades.split(',').filter(g => g.trim())
  } catch {
    return []
  }
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return '-'
  const date = new Date(dateStr)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  })
}

onMounted(() => {
  loadData()
})
</script>

<style lang="scss" scoped>
.teacher-page {
  .search-form {
    margin-bottom: 24px;
  }
  
  .teacher-table {
    margin-top: 16px;
  }
}
</style>

